package self.xine.basic.thread.entity;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程间共用的对象
 * @author xine
 * @date 2018年9月8日
 */
public class LockSharedObject {

	private int count = 10;	
	private Lock lock = new ReentrantLock();	
		
	public void add(int value) {
		lock.lock();
		
		try {
			if(value > 0) {
				count += value;
			}
		}finally {
			lock.unlock();
		}	
	}
	
	public int sub(int value) {
		lock.lock();		
		try {
			if(count - value >= 0) {
				count-= value;
			}
			return count;
		}finally {
			lock.unlock();
		}		
	}
	
	public void set(int value) {
		lock.lock();
		
		try {
			if(value >= 0) {
				count = value;
			}
		}finally {
			lock.unlock();
		}
	}
	
	public synchronized int getCount() {
		return count;
	}
	
}
